package com.jiaquyun.jcyx.main.cart

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.TimeUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.Address
import com.jiaquyun.jcyx.entity.CartId
import com.jiaquyun.jcyx.entity.CartSettlement
import com.jiaquyun.jcyx.entity.OrderData
import com.jiaquyun.jcyx.jetpack.mode.OrderViewModel
import com.jiaquyun.jcyx.main.mine.AddressEditFragment
import com.jiaquyun.jcyx.main.mine.MineAddressActivity
import com.module.lemlin.LoadingDialog
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_cart_settlement.*
import java.lang.StringBuilder


class CartSettlementActivity : OwnerViewModeActivity<OrderViewModel>() {

    companion object {
        const val KEY_CART_SETTLEMENT = "KEY_CART_SETTLEMENT"
    }

    private val mCartSettlementAdapter = CartSettlementAdapter()

    private val mCartSettlement: CartSettlement? by lazy {
        intent?.extras?.getSerializable(KEY_CART_SETTLEMENT) as? CartSettlement
    }

    override fun viewModel(): OrderViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_cart_settlement

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flCartSettlementBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }

        mCartSettlement?.let {
            setFillData(it)
        }

        cbCartSettlementIntegral.setOnClickListener {
            mCartSettlement?.let {
                setBottomTotalPrice(it)
            }
        }

        cbCartSettlementBalance.setOnClickListener {
            mCartSettlement?.let {
                setBottomTotalPrice(it)
            }
        }
        tvCartSettlementSubmit.setOnClickListener {
            mCartSettlement?.let { cs ->
                val cartId = mutableListOf<String>()
                cs.goods_list.forEach {
                    cartId.add(it.cart_id.toString())
                }

                val orderData = OrderData(
                    address_id = cs.address?.id ?: 0,
                    cart_list = CartId(cartId),
                    deal_type = 0,
                    is_deduction_money = cbCartSettlementBalance.isChecked,
                    is_deduction_score = if (cbCartSettlementIntegral.isChecked) 1 else 0,
                    user_note = null,
                )
                viewModel.orderSubmit(orderData)
            }
        }
    }

    override fun initData() {

    }

    override fun initViewMode() {
        viewModel.orderSubmitLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(this, R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            viewModel.orderDetail(data.order_id)
        })

        viewModel.orderDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            LoadingDialog.dismiss()
            val data = response.data?.data ?: return@observe
            OrderPayActivity.open(data)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || requestCode != 1) {
            return
        }
        val address =
            (data?.extras?.getSerializable(AddressEditFragment.KEY_ADDRESS_EDIT) as? Address)
                ?: return
        val cs = mCartSettlement?.apply { this.address = address }
            ?: return
        setFillData(cs)

    }

    @SuppressLint("SetTextI18n")
    private fun setFillData(cs: CartSettlement) {

        val address = cs.address
        tvCartSettlementNamePhone.visibility = if (address == null)
            View.GONE else View.VISIBLE
        tvCartSettlementNamePhone.text = StringBuilder()
            .append(address?.consignee).append("/").append(address?.mobile)
        tvCartSettlementAddress.text =
            address?.full_address ?: "请选择收货地址"

        val time = if (cs.order_delivery_time.isNullOrEmpty()) {
            System.currentTimeMillis() + 60 * 60 * 1000
        } else {
            System.currentTimeMillis() + cs.order_delivery_time.toInt() * 60 * 1000
        }

        tvCartSettlementDate.text =
            "尽快送达\t预计${TimeUtils.millis2String(time, "HH:mm")}"

        tvCartSettlementGoodsCount.text =
            StringBuilder().append("共").append(cs.total_num).append("件")
        tvCartSettlementGoodsPrice.text =
            StringBuilder().append("￥").append(cs.goods_fee)

        val couponList = cs.coupon_list
        tvCartSettlementCoupon.text = if (couponList.isNullOrEmpty())
            "暂无可用优惠券" else StringBuilder().append("共")
            .append(couponList.size).append("张可用")
        val isDelivery = (cs.goods_fee).toDouble() <
                (cs.free_delivery).toDouble()
        tvCartSettlementPriceDelivery.text = StringBuilder().append("￥")
            .append(if (isDelivery) cs.delivery_money else "0")
        tvCartSettlementPriceFull.text =
            StringBuilder().append("￥").append(cs.discount)
        val score = ((cs.score) *
                (cs.order_score_deduction_rate).toDouble() / 100).toInt()
        tvCartSettlementPriceIntegral.text =
            StringBuilder().append("积分抵扣(￥").append(score).append(")")
        tvCartSettlementPriceBalance.text =
            StringBuilder().append("余额抵扣(￥").append(cs.money).append(")")
        setBottomTotalPrice(cs)

        val goodsList = cs.goods_list
        rvCartSettlementGoodsBody.adapter = mCartSettlementAdapter.apply {
            setNewInstance(goodsList)
        }

        llCartSettlementAddress.setOnClickListener {
            MineAddressActivity.open(activity = this, action = 1)
        }
        ivCartSettlementAddress.setOnClickListener {
            MineAddressActivity.open(activity = this, action = 1)
        }
    }

    private fun setBottomTotalPrice(cs: CartSettlement) {

        val isDelivery = (cs.goods_fee).toDouble() <
                (cs.free_delivery).toDouble()

        var totalPrice = if (isDelivery) (cs.goods_fee).toDouble() +
                (cs.delivery_money).toDouble() else
            (cs.goods_fee).toDouble()

        val scorePrice = ((cs.score) *
                (cs.order_score_deduction_rate).toDouble() / 100).toInt()
        totalPrice = if (cbCartSettlementIntegral.isChecked)
            (totalPrice - scorePrice.toDouble()) else totalPrice

        val moneyPrice = (cs.money).toDouble()
        totalPrice = if (cbCartSettlementBalance.isChecked)
            (totalPrice - moneyPrice) else totalPrice

        tvCartSettlementPrice.text = if (totalPrice <= 0) {
            "￥0.00"
        } else StringBuilder().append("￥").append(totalPrice)

    }
}

